package cn.dogger.easyboot.netty.chat;

import cn.dogger.easyboot.netty.handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.util.Scanner;

/**
 * @author dogger
 * 2022/11/25 18:05
 */
public class NettyClient {
    /**
     * 注: 服务端配置了HTTP请求编解码器后客户端能连上但无法使用...
     * @param args
     */
    public static void main(String[] args) {
        //线程组workerGroup处理与客户端的业务来往
        EventLoopGroup clientGroup = new NioEventLoopGroup(10);

        //创建服务端启动对象
        Bootstrap bootstrap = new Bootstrap();
        //设置参数
        bootstrap
                //设置线程组
                .group(clientGroup)
                //使用NioSocketChannel作为客户端通道实现
                .channel(NioSocketChannel.class)
                //创建通道并初始化对象,设置初始化参数
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();

                        pipeline //对workerGroup的SocketChannel设置处理类
                                .addLast(new NettyClientHandler())
                                // 文件分块传输,对写大数据流的支持
                                .addFirst(new ChunkedWriteHandler())
                                //respon解码
                                .addLast(new HttpResponseDecoder())
                               ;
                        //加入解码器
                        pipeline.addLast("decoder", new StringDecoder());
                        //加入编码器
                        pipeline.addLast("encoder", new StringEncoder());
                    }
                });
        try {
            //连接服务端
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8989).sync();
            //拿到channel
            Channel channel = channelFuture.channel();
            System.out.println("当前客户端ip地址和端口: " + channel.localAddress() + "\n");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            clientGroup.shutdownGracefully();
        }

    }
}
